import { fetchMenuList } from '@/api/menu'

const state = {
  menuList: []
}

function convertMenu(data, parentIndex = '') {
  // 递归转换后端菜单为前端格式
  return data.map((item, idx) => {
    const index = parentIndex ? `${parentIndex}-${idx + 1}` : `${idx + 1}`
    const menu = {
      name: item.name,
      index,
      // 路由path优先取path字段，否则用menuCode映射
      path: getPathByMenu(item),
    }
    if (item.childMenu && Array.isArray(item.childMenu) && item.childMenu.length > 0) {
      menu.children = convertMenu(item.childMenu, index)
    }
    return menu
  })
}

// 你可以根据实际路由规则自定义映射
function getPathByMenu(item) {
  // 这里假设menuCode和路由一一对应
  const codeToPath = {
    '': '/',
    'userManage': '/user-manage',
    'roleManage': '/role-manage',
    'stockList': '/stock',
    'sysManage': '', // 目录不跳转
    'stockSys': '',  // 目录不跳转
    'homePage': '/home'
  }
  if (item.path) return item.path
  if (item.menuCode && codeToPath[item.menuCode] !== undefined) return codeToPath[item.menuCode]
  return '/'
}

const mutations = {
  SET_MENU_LIST(state, menuList) {
    state.menuList = menuList
  }
}

const actions = {
  async getMenuList({ commit }) {
    const res = await fetchMenuList()
    // 兼容有data字段的返回
    const rawMenu = Array.isArray(res.data) ? res.data : (res.data.data || [])
    const menuList = convertMenu(rawMenu)
    commit('SET_MENU_LIST', menuList)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 